package com.zzyl.nursing.service.impl.member;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.member.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatServiceImpl implements IWeChatService {


    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String appsecret;
    @Value("${wechat.getopenid_url}")
    private String getopenidurl;
    @Value("${wechat.getphonenumber_url}")
    private String getphonenumber;
    @Value("${wechat.getaccesstoken_url}")
    private String getaccesstoken;

    /**
     * 获取 用户登录唯一凭证 OpenId
     *
     * @return
     */
    @Override
    public String getOpenId(String code) {
        log.info("正在获取用户登录唯一凭证OpenId···");
        String url = getopenidurl + "?grant_type=" + "authorization_code";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("appid", appid);
        paramMap.put("secret", appsecret);
        paramMap.put("js_code", code);
        String result = HttpUtil.createRequest(Method.GET, url).form(paramMap).execute().body();
        JSONObject object = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty( object.getInt("errcode"))){
            // 获取失败 抛出鸭肠
            log.error("获取用户登录唯一凭证OpenId失败");
            throw new BaseException(object.getStr("errmsg"));
        }
        String openid = object.getStr("openid");
        log.info("获取用户登录唯一凭证OpenId成功: {}", openid);
        return openid;
    }

    /**
     * 获取 手机号
     * @param detailCode 详情code
     * @return
     */
    @Override
    public String getPhone(String detailCode) {

        log.info("正在获取手机号···");
        String url = getphonenumber + getAccessToken();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("code", detailCode);
        String body = HttpUtil.createPost(url)
                .body(JSONUtil.toJsonStr(paramMap))
                .execute()
                .body();
        if(!ObjectUtil.isNotEmpty( body)){
            throw new BaseException("获取手机号失败");
        }

        // 获取响应成功 转换为JOSN对象
        JSONObject jsonObject = JSONUtil.parseObj(body);
        // 判断是否成功
        if(!ObjectUtil.equals( jsonObject.getInt("errcode"), 0)){
            // 获取失败 抛出异常
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        log.info("手机号获取成功: {}", phone);
        // 返回响应体中的手机号
        return phone;
    }


    /**
     * 获取 access_token
     * @return
     */
    private String getAccessToken() {

        log.info("正在获取access_token···");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("appid", appid);
        paramMap.put("secret", appsecret);
        paramMap.put("grant_type", "client_credential");
        String body = HttpUtil.get(getaccesstoken, paramMap);
        if(!ObjectUtil.isNotEmpty( body)){
            throw new BaseException("获取access_token失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(body);

        // 返回响应体中的access_token
        String accessToken = jsonObject.getStr("access_token");
        log.info("access_token获取成功: {}", accessToken);
        return accessToken;

    }


}
